package com.atguigu.tingshu.order.listener;

import com.atguigu.tingshu.common.constant.RabbitConstant;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.model.order.OrderInfo;
import com.atguigu.tingshu.order.service.OrderInfoService;
import com.atguigu.tingshu.order.service.impl.OrderInfoServiceImpl;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Slf4j
@Component
public class OrderMQListener {

    @Autowired
    private OrderInfoService orderInfoService;

    // 消费死信队列
    @RabbitListener(queues = RabbitConstant.ORDER_DEAD_QUEUE)
    @SneakyThrows
    public void cancelOrder(Channel channel, Message message, String orderNo) {
        log.info("订单支付成功，订单id：{}", orderNo);
        // 延时关单 orderNo  根据tradeNo查询订单，如果订单状态是未支付，更新订单状态为取消订单
        try {
            // 修改订单的状态为已取消
            orderInfoService.update(new LambdaUpdateWrapper<OrderInfo>()
                    .eq(OrderInfo::getOrderNo, orderNo)
                    .eq(OrderInfo::getOrderStatus, SystemConstant.ORDER_STATUS_UNPAID)
                    .set(OrderInfo::getOrderStatus, SystemConstant.ORDER_STATUS_CANCEL));
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            if (message.getMessageProperties().isRedelivered()) {

                channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
                log.error("订单支付超时,延迟关单失败.....，订单id：{}", orderNo);

            } else {

                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
                log.warn("订单支付超时,正在重试..............，订单id：{}", orderNo);

            }
        }
    }
}
